package metric

import (
	"gddgame.cc/galaxy/binocle"
	"github.com/pkg/errors"
	"github.com/toolkits/nux"
)

func Df(agent binocle.Service) error {
	mountPoints, err := nux.ListMountPoint()

	if err != nil {
		return errors.New("collect device metrics fail:" + err.Error())
	}

	agent.AddMetrics().Collect(func() map[string]float32 {
		var diskTotal uint64 = 0
		var diskUsed uint64 = 0

		for idx := range mountPoints {
			fsSpec, fsFile, fsVfstype := mountPoints[idx][0], mountPoints[idx][1], mountPoints[idx][2]

			var du *nux.DeviceUsage
			du, err = nux.BuildDeviceUsage(fsSpec, fsFile, fsVfstype)
			if err != nil {
				continue
			}

			if du.BlocksAll == 0 {
				continue
			}

			diskTotal += du.BlocksAll
			diskUsed += du.BlocksUsed
		}

		return map[string]float32{
			"df.statistics.total":        float32(diskTotal),
			"df.statistics.used":         float32(diskUsed),
			"df.statistics.used.percent": float32(diskUsed) * 100.0 / float32(diskTotal),
		}
	})
	return nil

}
